"""WRITE task executor instruction seed prompt for DSPy.

This module provides an optimized instruction prompt and demos specifically
for WRITE tasks - documentation, reports, summaries, and clear communication.
"""

import dspy

EXECUTOR_WRITE_PROMPT = r"""
# Executor (WRITE) — Instruction Prompt

Role
Execute WRITE tasks: create documentation, reports, summaries, and clear written communication across various formats and audiences.

Task Characteristics (WRITE)
- Primary goal: Produce clear, well-structured written content that serves its purpose
- Audience-aware: Adapt tone, style, and complexity to target readers
- Purpose-driven: Content serves specific goal (inform, document, persuade, instruct)
- Format-flexible: Technical docs, business reports, user guides, summaries, articles

Execution Guidelines (WRITE-Specific)
1. Audience analysis: Understand who will read this and what they need
2. Purpose clarity: Define what the document should accomplish
3. Structure first: Outline before writing (hierarchy, sections, flow)
4. Clarity over cleverness: Simple, direct language; avoid unnecessary jargon
5. Active voice: "The system processes requests" not "Requests are processed by the system"
6. Concrete examples: Use specific examples, not abstract descriptions
7. Visual hierarchy: Use headings, bullets, tables, and formatting for scanability

Output Contract (strict)
- `output` (string): Well-structured written content in appropriate format
- `sources` (list[str]): Reference materials, data sources, or documentation consulted

Quality Standards (WRITE)
- Clarity: Complex ideas explained simply; no ambiguity
- Completeness: All necessary information included; no critical gaps
- Accuracy: Facts verified, claims supported, technical details correct
- Organization: Logical flow, clear sections, easy navigation
- Conciseness: No unnecessary words; respect reader's time
- Consistency: Terminology, style, and formatting uniform throughout

Common WRITE Patterns
- Technical documentation: Define scope → Explain concepts → Provide examples → Document edge cases → Include troubleshooting
- Business report: Executive summary → Background/context → Analysis → Findings → Recommendations
- User guide: Overview → Prerequisites → Step-by-step instructions → Screenshots/examples → FAQs
- API documentation: Endpoint description → Parameters → Request/response examples → Error codes
- Summary: Read source → Extract key points → Organize logically → Write concisely → Verify accuracy

Writing Best Practices
- Lead with most important information (inverted pyramid)
- One idea per paragraph
- Use transition words for flow (however, therefore, additionally)
- Define acronyms on first use
- Include code examples for technical content
- Add tables for comparison or reference data
- Use numbered lists for sequences, bullets for unordered items
- End with clear next steps or conclusion

Format-Specific Guidelines
- README: Purpose, installation, quickstart, examples, contributing
- API docs: Authentication, endpoints, parameters, responses, errors
- Changelog: Version, date, added/changed/fixed/deprecated/removed
- User guide: Task-oriented, step-by-step, screenshots, troubleshooting
- Report: Executive summary, methodology, findings, recommendations
- Tutorial: Learning objectives, prerequisites, incremental steps, exercises
"""

EXECUTOR_WRITE_DEMOS = [
    # Demo 1: Technical documentation (API)
    dspy.Example(
        goal="Write API documentation for a cryptocurrency price endpoint",
        output=(
            "# GET /api/v1/crypto/price\n\n"
            "Retrieve real-time cryptocurrency prices in multiple fiat currencies.\n\n"
            "## Request\n\n"
            "**Endpoint**: `GET https://api.example.com/v1/crypto/price`\n\n"
            "**Query Parameters**:\n\n"
            "| Parameter | Type | Required | Description |\n"
            "|-----------|------|----------|-------------|\n"
            "| symbols | string | Yes | Comma-separated crypto symbols (e.g., BTC,ETH,SOL) |\n"
            "| currency | string | No | Fiat currency code (default: USD) |\n"
            "| include_24h_change | boolean | No | Include 24h price change (default: false) |\n\n"
            "**Example Request**:\n"
            "```bash\n"
            "curl 'https://api.example.com/v1/crypto/price?symbols=BTC,ETH&currency=USD&include_24h_change=true'\n"
            "```\n\n"
            "## Response\n\n"
            "**Success (200 OK)**:\n"
            "```json\n"
            "{\n"
            "  \"data\": [\n"
            "    {\n"
            "      \"symbol\": \"BTC\",\n"
            "      \"price\": 43521.37,\n"
            "      \"currency\": \"USD\",\n"
            "      \"change_24h\": 2.34,\n"
            "      \"timestamp\": \"2025-10-20T14:32:00Z\"\n"
            "    },\n"
            "    {\n"
            "      \"symbol\": \"ETH\",\n"
            "      \"price\": 2287.56,\n"
            "      \"currency\": \"USD\",\n"
            "      \"change_24h\": 1.87,\n"
            "      \"timestamp\": \"2025-10-20T14:32:00Z\"\n"
            "    }\n"
            "  ],\n"
            "  \"rate_limit\": {\n"
            "    \"remaining\": 98,\n"
            "    \"reset\": \"2025-10-20T15:00:00Z\"\n"
            "  }\n"
            "}\n"
            "```\n\n"
            "**Error Responses**:\n\n"
            "| Status | Code | Description |\n"
            "|--------|------|-------------|\n"
            "| 400 | INVALID_SYMBOL | One or more crypto symbols not recognized |\n"
            "| 429 | RATE_LIMIT_EXCEEDED | API rate limit exceeded (100 requests/hour) |\n"
            "| 503 | SERVICE_UNAVAILABLE | Upstream price feed temporarily unavailable |\n\n"
            "## Rate Limits\n\n"
            "- Free tier: 100 requests/hour\n"
            "- Pro tier: 1,000 requests/hour\n"
            "- Enterprise: Custom limits\n\n"
            "## Supported Symbols\n\n"
            "BTC, ETH, SOL, AVAX, MATIC, ADA, DOT, LINK, UNI, AAVE (50+ total - see full list)\n\n"
            "## Supported Currencies\n\n"
            "USD, EUR, GBP, JPY, CNY, KRW, INR, AUD, CAD, CHF"
        ),
        sources=["Internal API specification", "CoinGecko API reference", "REST API best practices"]
    ).with_inputs("goal"),

    # Demo 2: README documentation (crypto toolkit)
    dspy.Example(
        goal="Write a README for a Python library that analyzes DeFi protocols",
        output=(
            "# DeFi Analytics SDK\n\n"
            "Python toolkit for analyzing DeFi protocols across multiple blockchains.\n\n"
            "## Features\n\n"
            "- **Multi-chain support**: Ethereum, BSC, Polygon, Arbitrum, Optimism\n"
            "- **Protocol analytics**: TVL, volume, fees, user metrics\n"
            "- **Historical data**: Query time-series data for trend analysis\n"
            "- **Real-time updates**: WebSocket support for live protocol stats\n"
            "- **Easy integration**: Simple Python API with async support\n\n"
            "## Installation\n\n"
            "```bash\n"
            "pip install defi-analytics-sdk\n"
            "```\n\n"
            "**Requirements**: Python 3.9+\n\n"
            "## Quick Start\n\n"
            "```python\n"
            "from defi_analytics import DeFiClient\n\n"
            "# Initialize client\n"
            "client = DeFiClient(api_key='your_api_key')\n\n"
            "# Get Uniswap TVL\n"
            "tvl = client.get_protocol_tvl('uniswap')\n"
            "print(f'Uniswap TVL: ${tvl:,.0f}')\n"
            "# Output: Uniswap TVL: $3,847,000,000\n\n"
            "# Get historical data\n"
            "history = client.get_tvl_history(\n"
            "    protocol='aave',\n"
            "    days=30\n"
            ")\n\n"
            "# Compare protocols\n"
            "comparison = client.compare_protocols(\n"
            "    protocols=['uniswap', 'aave', 'compound'],\n"
            "    metrics=['tvl', 'volume_24h', 'fees_24h']\n"
            ")\n"
            "```\n\n"
            "## Supported Protocols\n\n"
            "**DEXs**: Uniswap, SushiSwap, Curve, Balancer, PancakeSwap  \n"
            "**Lending**: Aave, Compound, MakerDAO, Euler  \n"
            "**Derivatives**: dYdX, GMX, Synthetix  \n"
            "**Yield**: Yearn, Convex, Lido, Rocket Pool\n\n"
            "## Examples\n\n"
            "**Get protocol metrics**:\n"
            "```python\n"
            "metrics = client.get_metrics('aave')\n"
            "print(f\"TVL: ${metrics.tvl:,.0f}\")\n"
            "print(f\"24h Volume: ${metrics.volume_24h:,.0f}\")\n"
            "print(f\"Active Users: {metrics.users_24h:,}\")\n"
            "```\n\n"
            "**Track yield farms**:\n"
            "```python\n"
            "farms = client.get_yield_farms(\n"
            "    min_apy=20,  # Minimum 20% APY\n"
            "    min_tvl=1_000_000  # At least $1M TVL\n"
            ")\n\n"
            "for farm in farms:\n"
            "    print(f\"{farm.protocol}: {farm.apy}% APY\")\n"
            "```\n\n"
            "**Real-time updates**:\n"
            "```python\n"
            "async def track_uniswap():\n"
            "    async for update in client.stream_protocol('uniswap'):\n"
            "        print(f\"TVL: ${update.tvl:,.0f}\")\n\n"
            "import asyncio\n"
            "asyncio.run(track_uniswap())\n"
            "```\n\n"
            "## API Reference\n\n"
            "See [full documentation](https://docs.defi-analytics.io)\n\n"
            "## License\n\n"
            "MIT License - see [LICENSE](LICENSE)"
        ),
        sources=["DeFiLlama API docs", "Web3.py patterns", "Python SDK best practices"]
    ).with_inputs("goal"),

    # Demo 3: Business report (crypto market)
    dspy.Example(
        goal="Write a quarterly DeFi market report summary",
        output=(
            "# Q3 2024 DeFi Market Report\n\n"
            "## Executive Summary\n\n"
            "Total Value Locked (TVL) in DeFi reached $87.3B in Q3 2024, up 34% from Q2. Growth driven by "
            "Ethereum Layer 2 adoption (+112%) and real-world asset (RWA) tokenization (+89%). Lending protocols "
            "saw increased institutional participation, while DEX volumes recovered to 2021 levels.\n\n"
            "**Key Metrics**:\n"
            "- Total DeFi TVL: $87.3B (+34% QoQ, +56% YoY)\n"
            "- DEX Volume: $412B (+45% QoQ)\n"
            "- Active Users: 6.8M (+22% QoQ)\n"
            "- Ethereum L2 TVL: $23.4B (+112% QoQ)\n"
            "- RWA Tokenization: $4.2B (+89% QoQ)\n\n"
            "## TVL Breakdown by Category\n\n"
            "| Category | Q3 2024 TVL | Q2 2024 TVL | Growth | Market Share |\n"
            "|----------|-------------|-------------|--------|-------------|\n"
            "| Lending | $32.1B | $26.5B | +21% | 37% |\n"
            "| DEXs | $28.7B | $21.3B | +35% | 33% |\n"
            "| Staking | $18.9B | $14.2B | +33% | 22% |\n"
            "| Derivatives | $5.4B | $3.8B | +42% | 6% |\n"
            "| RWA | $2.2B | $1.2B | +83% | 3% |\n\n"
            "**Analysis**:\n"
            "- Lending dominance continues; Aave and Compound lead with $18.4B combined TVL\n"
            "- DEX growth driven by Uniswap v4 launch and improved UX\n"
            "- Liquid staking (Lido, Rocket Pool) accounts for 78% of staking TVL\n\n"
            "## Chain Distribution\n\n"
            "| Blockchain | TVL | Share | QoQ Growth |\n"
            "|------------|-----|-------|------------|\n"
            "| Ethereum | $52.3B | 60% | +18% |\n"
            "| Ethereum L2s | $23.4B | 27% | +112% |\n"
            "| BSC | $4.8B | 6% | -5% |\n"
            "| Solana | $3.2B | 4% | +67% |\n"
            "| Other | $3.6B | 4% | +22% |\n\n"
            "**L2 Breakdown**:\n"
            "- Arbitrum: $12.1B (52% of L2 TVL)\n"
            "- Optimism: $6.8B (29%)\n"
            "- Base: $3.2B (14%) - fastest growing\n"
            "- Polygon zkEVM: $1.3B (6%)\n\n"
            "## Key Trends\n\n"
            "**1. Institutional DeFi Adoption**\n"
            "- Institutional TVL: $12.4B (14% of total, +156% YoY)\n"
            "- Major entrants: BlackRock ($450M in RWA), Franklin Templeton ($280M)\n"
            "- Permissioned pools gaining traction (Aave Arc, Compound Treasury)\n\n"
            "**2. Real-World Asset Tokenization**\n"
            "- Treasury-backed tokens: $2.8B (Ondo, Mountain Protocol)\n"
            "- Tokenized real estate: $890M (+134% QoQ)\n"
            "- Private credit: $510M (institutional-only pools)\n\n"
            "**3. Layer 2 Migration**\n"
            "- 27% of DeFi now on L2s (up from 15% in Q2)\n"
            "- Transaction costs: $0.15 avg on L2 vs $3.40 on mainnet\n"
            "- User migration: 2.1M L2 users (+145% QoQ)\n\n"
            "## DEX Performance\n\n"
            "**Top DEXs by Volume (Q3 2024)**:\n\n"
            "| DEX | Volume | Market Share | Growth |\n"
            "|-----|--------|--------------|--------|\n"
            "| Uniswap | $187B | 45% | +52% |\n"
            "| Curve | $89B | 22% | +28% |\n"
            "| PancakeSwap | $54B | 13% | -8% |\n"
            "| Balancer | $38B | 9% | +41% |\n"
            "| SushiSwap | $44B | 11% | +19% |\n\n"
            "**Uniswap v4 Impact**:\n"
            "- Launched Aug 2024; captured $34B volume in first month\n"
            "- Hooks feature enabled 127 custom pool types\n"
            "- Average swap cost: $1.20 (40% reduction vs v3)\n\n"
            "## Risks & Challenges\n\n"
            "**1. Regulatory Uncertainty**\n"
            "- SEC enforcement actions against DeFi protocols continuing\n"
            "- EU MiCA regulations take effect Jan 2025 (compliance costs)\n\n"
            "**2. Smart Contract Risks**\n"
            "- $187M lost to exploits in Q3 (down from $342M in Q2)\n"
            "- Major incidents: Exactly Protocol ($12M), Prisma Finance ($11.6M)\n\n"
            "**3. Centralization Concerns**\n"
            "- Top 3 lending protocols control 68% of lending TVL\n"
            "- Frontend censorship incidents (dYdX, Uniswap)\n\n"
            "## Q4 Outlook\n\n"
            "**Projected TVL**: $95-105B (+9-20% QoQ)\n\n"
            "**Catalysts**:\n"
            "- Ethereum Dencun upgrade (further L2 cost reduction)\n"
            "- Institutional RWA products launching (Blackrock BUIDL expansion)\n"
            "- Potential regulatory clarity in US (election outcome dependent)\n\n"
            "**Risks**:\n"
            "- Macro headwinds (rate environment)\n"
            "- Continued regulatory pressure on US-based protocols\n\n"
            "## Recommendations\n\n"
            "1. **Watch L2 growth**: Arbitrum and Base gaining significant market share\n"
            "2. **RWA opportunity**: Institutional products showing strong demand\n"
            "3. **Risk management**: Smart contract audits critical as complexity increases\n"
            "4. **Diversification**: Reduce concentration risk in top protocols"
        ),
        sources=["DefiLlama", "Dune Analytics", "Token Terminal", "The Block Research", "Internal market analysis"]
    ).with_inputs("goal"),

    # Demo 4: User guide (wallet setup)
    dspy.Example(
        goal="Write a beginner's guide for setting up a MetaMask wallet",
        output=(
            "# MetaMask Wallet Setup Guide\n\n"
            "Learn how to create and secure your MetaMask cryptocurrency wallet in 10 minutes.\n\n"
            "**What is MetaMask?**  \n"
            "MetaMask is a browser extension wallet for storing Ethereum and ERC-20 tokens, and interacting with decentralized applications (dApps).\n\n"
            "**What you'll need**: \n"
            "- Chrome, Firefox, Brave, or Edge browser\n"
            "- Pen and paper for backup phrase (NEVER store digitally)\n\n"
            "---\n\n"
            "## Step 1: Install MetaMask Extension\n\n"
            "1. Go to [metamask.io](https://metamask.io)\n"
            "2. Click **Download** → Select your browser\n"
            "3. Click **Add to Chrome** (or your browser)\n"
            "4. Click **Add Extension** when prompted\n\n"
            "**Verify legitimacy**: Check URL is exactly `metamask.io` (beware of phishing sites)\n\n"
            "---\n\n"
            "## Step 2: Create New Wallet\n\n"
            "1. MetaMask opens automatically (or click fox icon in browser toolbar)\n"
            "2. Click **Get Started**\n"
            "3. Select **Create a new wallet**\n"
            "4. Choose whether to share analytics (optional)\n"
            "5. Create a strong password (min 8 characters)\n"
            "6. Click **Create a new wallet**\n\n"
            "**Password tip**: Use unique password not used elsewhere; consider a password manager\n\n"
            "---\n\n"
            "## Step 3: Secure Your Recovery Phrase (CRITICAL)\n\n"
            "**What is a recovery phrase?**  \n"
            "12 words that act as master key to your wallet. Anyone with this phrase controls your funds.\n\n"
            "**Steps**:\n"
            "1. Click **Secure my wallet**\n"
            "2. Watch the security video (recommended)\n"
            "3. Click **Reveal Secret Recovery Phrase**\n"
            "4. **Write down all 12 words ON PAPER in exact order**\n"
            "5. Store paper in secure location (safe, safety deposit box)\n"
            "6. Click **Next**\n"
            "7. Verify by selecting words in correct order\n"
            "8. Click **Confirm**\n\n"
            "**⚠️ CRITICAL SECURITY RULES**:\n\n"
            "✅ DO:\n"
            "- Write on paper and store securely offline\n"
            "- Consider making duplicate backup in separate location\n"
            "- Use metal backup for fire/water resistance (optional)\n\n"
            "❌ NEVER:\n"
            "- Take screenshot or photo of recovery phrase\n"
            "- Store in email, cloud storage, or note apps\n"
            "- Share with ANYONE (MetaMask will never ask for it)\n"
            "- Enter into websites claiming to \"validate\" your wallet\n\n"
            "---\n\n"
            "## Step 4: Explore Your Wallet\n\n"
            "**Main Screen**:\n"
            "- **Account name**: Default is \"Account 1\" (click to rename)\n"
            "- **Address**: Your wallet address (starts with 0x...)\n"
            "- **Balance**: Shows ETH balance and token values\n"
            "- **Networks**: Top left dropdown (Ethereum Mainnet default)\n\n"
            "**Copy your address**:\n"
            "1. Click your account name at top\n"
            "2. Click copy icon next to address\n"
            "3. Your address is now copied (use to receive funds)\n\n"
            "---\n\n"
            "## Step 5: Add Funds to Your Wallet\n\n"
            "**Option 1: Buy crypto directly (easiest)**\n"
            "1. Click **Buy** button in MetaMask\n"
            "2. Select provider (Moonpay, Transak, etc.)\n"
            "3. Complete KYC and payment\n\n"
            "**Option 2: Transfer from exchange**\n"
            "1. Copy your MetaMask address (Step 4)\n"
            "2. Go to your exchange (Coinbase, Binance, etc.)\n"
            "3. Navigate to **Withdraw** → Select **ETH**\n"
            "4. Paste MetaMask address\n"
            "5. Select **Ethereum (ERC-20)** network\n"
            "6. Confirm withdrawal\n\n"
            "**⚠️ Important**: Always send small test amount first ($10-20) to verify address\n\n"
            "---\n\n"
            "## Step 6: Add Custom Tokens\n\n"
            "MetaMask shows ETH by default. To see other tokens:\n\n"
            "1. Scroll to bottom → Click **Import tokens**\n"
            "2. Search for token name (e.g., \"USDC\")\n"
            "3. Click token → **Next** → **Import**\n\n"
            "**Manual import** (if token not found):\n"
            "1. Click **Custom token** tab\n"
            "2. Paste token contract address (find on Etherscan)\n"
            "3. Symbol and decimals auto-fill\n"
            "4. Click **Import**\n\n"
            "---\n\n"
            "## Security Best Practices\n\n"
            "**1. Verify Websites**\n"
            "- Check URL carefully before connecting wallet (phishing sites common)\n"
            "- Look for HTTPS lock icon\n"
            "- Bookmark frequently used dApps\n\n"
            "**2. Review Transactions**\n"
            "- Always check recipient address before confirming\n"
            "- Review gas fees (extremely high = possible scam)\n"
            "- Understand what contract you're approving\n\n"
            "**3. Use Hardware Wallet**\n"
            "- For large amounts, connect Ledger or Trezor to MetaMask\n"
            "- MetaMask Settings → Advanced → Connect hardware wallet\n\n"
            "**4. Revoke Token Approvals**\n"
            "- Periodically check approved contracts: [revoke.cash](https://revoke.cash)\n"
            "- Revoke unused approvals to limit risk\n\n"
            "---\n\n"
            "## Troubleshooting\n\n"
            "**Transaction stuck/pending?**\n"
            "- Click transaction → **Speed Up** (increases gas)\n"
            "- Or wait; transactions eventually process or fail\n\n"
            "**Wrong network?**\n"
            "- Click network dropdown (top left)\n"
            "- Select correct network (Ethereum, Polygon, etc.)\n\n"
            "**Lost access?**\n"
            "- If you have recovery phrase: Reinstall MetaMask → Import wallet\n"
            "- No recovery phrase = funds unrecoverable (no customer support can help)\n\n"
            "---\n\n"
            "## Next Steps\n\n"
            "- **Try a dApp**: [Uniswap](https://uniswap.org) for token swaps\n"
            "- **Learn about gas**: [ETH Gas Station](https://ethgasstation.info)\n"
            "- **Join community**: [MetaMask Discord](https://discord.gg/metamask)\n\n"
            "**Remember**: You are your own bank. No one can recover lost funds or reset passwords. Security is YOUR responsibility."
        ),
        sources=["MetaMask official documentation", "Web3 security best practices", "Cryptocurrency beginner guides"]
    ).with_inputs("goal"),

    # Demo 5: Summary (protocol analysis)
    dspy.Example(
        goal="Summarize how Uniswap v3 concentrated liquidity works",
        output=(
            "# Uniswap v3 Concentrated Liquidity - Summary\n\n"
            "## Overview\n\n"
            "Uniswap v3 introduces **concentrated liquidity**, allowing liquidity providers (LPs) to allocate capital "
            "within specific price ranges instead of across the entire 0 to ∞ curve. This dramatically improves capital "
            "efficiency and LP returns.\n\n"
            "---\n\n"
            "## Key Concept: Price Ranges\n\n"
            "**Uniswap v2** (old model):\n"
            "- LPs provide liquidity across entire price curve (0 to infinity)\n"
            "- Example: Provide $1000 USDC + 0.5 ETH\n"
            "- Liquidity active whether ETH is $100 or $10,000\n"
            "- Most capital sits idle (never used)\n\n"
            "**Uniswap v3** (concentrated liquidity):\n"
            "- LPs choose price range (e.g., $1,800 - $2,200 for ETH/USDC)\n"
            "- Liquidity only active within chosen range\n"
            "- Same capital generates 100-4000x more fees (depending on range width)\n\n"
            "---\n\n"
            "## How It Works\n\n"
            "**1. LP Selects Price Range**\n\n"
            "```\n"
            "Example: ETH/USDC pool, current price $2,000\n\n"
            "LP chooses range: $1,900 - $2,100\n\n"
            "├─────────┼─────────┼─────────┼─────────┼─────────┤\n"
            "$1,700   $1,900   $2,000   $2,100   $2,300\n"
            "         └─────── Active ───────┘\n"
            "                   (LP earns fees here)\n"
            "```\n\n"
            "**2. Capital Efficiency**\n\n"
            "Narrow range = Higher capital efficiency:\n\n"
            "| Price Range | Capital Efficiency vs v2 |\n"
            "|-------------|-------------------------|\n"
            "| $1,800 - $2,200 (±10%) | ~200x |\n"
            "| $1,900 - $2,100 (±5%) | ~400x |\n"
            "| $1,950 - $2,050 (±2.5%) | ~800x |\n"
            "| $1,990 - $2,010 (±0.5%) | ~4,000x |\n\n"
            "**Trade-off**: Narrower range = higher returns BUT higher risk of price moving outside range\n\n"
            "**3. Out of Range Behavior**\n\n"
            "When price exits LP's range:\n"
            "- LP stops earning fees (liquidity inactive)\n"
            "- Position converts to 100% of one asset\n"
            "- LP must rebalance (withdraw and deposit in new range)\n\n"
            "Example:\n"
            "```\n"
            "Initial: $1,000 USDC + 0.5 ETH at $2,000 (range: $1,900-$2,100)\n\n"
            "If ETH rises to $2,300:\n"
            "- Position becomes: ~1.05 ETH + $0 USDC\n"
            "- No longer earning fees\n"
            "- Need to create new position at higher range\n"
            "```\n\n"
            "---\n\n"
            "## Fee Tiers\n\n"
            "Uniswap v3 offers multiple fee tiers for different asset pairs:\n\n"
            "| Fee Tier | Best For | Example Pairs |\n"
            "|----------|----------|---------------|\n"
            "| 0.01% | Stablecoins | USDC/USDT, DAI/USDC |\n"
            "| 0.05% | Correlated assets | WETH/stETH, WBTC/renBTC |\n"
            "| 0.30% | Standard pairs | ETH/USDC, ETH/DAI |\n"
            "| 1.00% | Exotic/volatile | Altcoins, new tokens |\n\n"
            "Higher fee = Compensates for higher volatility and impermanent loss risk\n\n"
            "---\n\n"
            "## Benefits\n\n"
            "**For Liquidity Providers**:\n"
            "- 100-4000x capital efficiency (more fees from same capital)\n"
            "- Customizable risk/reward (choose your price range and fee tier)\n"
            "- Potential for higher APY than v2\n\n"
            "**For Traders**:\n"
            "- Better execution prices (more concentrated liquidity at current price)\n"
            "- Lower slippage on large trades\n"
            "- More competitive pricing vs CEXs\n\n"
            "---\n\n"
            "## Challenges\n\n"
            "**1. Active Management Required**\n"
            "- Price can exit range → Must rebalance frequently\n"
            "- Not \"set and forget\" like v2\n"
            "- Gas costs for rebalancing can eat profits\n\n"
            "**2. Complexity**\n"
            "- Requires understanding of price ranges, impermanent loss, fee tiers\n"
            "- Easy to make mistakes (wrong range, wrong fee tier)\n\n"
            "**3. Impermanent Loss**\n"
            "- Still exists (can be amplified with narrow ranges)\n"
            "- If price trends strongly in one direction, losses can exceed fees earned\n\n"
            "---\n\n"
            "## Example Strategy\n\n"
            "**Conservative ETH/USDC LP**:\n\n"
            "- Current ETH price: $2,000\n"
            "- Choose range: $1,600 - $2,400 (±20%)\n"
            "- Fee tier: 0.30%\n"
            "- Rebalance: Only if price exits range\n\n"
            "**Expected**:\n"
            "- ~50-100x capital efficiency vs v2\n"
            "- Lower maintenance (wide range)\n"
            "- Lower fees earned per dollar, but less active management\n\n"
            "**Aggressive ETH/USDC LP**:\n\n"
            "- Current ETH price: $2,000\n"
            "- Choose range: $1,950 - $2,050 (±2.5%)\n"
            "- Fee tier: 0.30%\n"
            "- Rebalance: Daily or when price nears boundary\n\n"
            "**Expected**:\n"
            "- ~800x capital efficiency vs v2\n"
            "- High maintenance (frequent rebalancing)\n"
            "- Very high fees earned per dollar, but requires active monitoring\n\n"
            "---\n\n"
            "## Bottom Line\n\n"
            "Uniswap v3 concentrated liquidity is powerful but requires:\n"
            "- **Understanding**: Know your price range strategy\n"
            "- **Active management**: Monitor and rebalance positions\n"
            "- **Risk awareness**: Impermanent loss and out-of-range risks\n\n"
            "**Best for**: Experienced LPs willing to actively manage positions  \n"
            "**Not ideal for**: Set-and-forget passive LPs (consider v2 or managed vaults instead)"
        ),
        sources=["Uniswap v3 whitepaper", "Uniswap documentation", "DeFi education resources"]
    ).with_inputs("goal"),

    # Demo 6: Tutorial (token swap)
    dspy.Example(
        goal="Write a tutorial for swapping tokens on Uniswap",
        output=(
            "# How to Swap Tokens on Uniswap\n\n"
            "Learn how to exchange cryptocurrencies using Uniswap, a decentralized exchange (DEX).\n\n"
            "**What you'll need**:\n"
            "- MetaMask wallet (or compatible Web3 wallet)\n"
            "- ETH for gas fees (~$5-20 depending on network congestion)\n"
            "- Tokens to swap\n\n"
            "**Time**: 5 minutes\n\n"
            "---\n\n"
            "## Step 1: Go to Uniswap\n\n"
            "1. Navigate to [app.uniswap.org](https://app.uniswap.org)\n"
            "2. Click **Launch App** (top right)\n\n"
            "**⚠️ Security**: Verify URL is exactly `app.uniswap.org` (beware of phishing sites like `unιswap.org`)\n\n"
            "---\n\n"
            "## Step 2: Connect Your Wallet\n\n"
            "1. Click **Connect Wallet** (top right)\n"
            "2. Select **MetaMask** (or your wallet)\n"
            "3. Approve connection in MetaMask popup\n"
            "4. Your wallet address and balance appear in top right\n\n"
            "---\n\n"
            "## Step 3: Select Tokens to Swap\n\n"
            "**Top field** (\"You pay\"):\n"
            "1. Click token dropdown (defaults to ETH)\n"
            "2. Search for token you want to SELL (e.g., \"USDC\")\n"
            "3. Click token to select\n"
            "4. Enter amount or click **Max** to swap entire balance\n\n"
            "**Bottom field** (\"You receive\"):\n"
            "1. Click token dropdown\n"
            "2. Search for token you want to BUY (e.g., \"UNI\")\n"
            "3. Click token to select\n"
            "4. Estimated output amount appears automatically\n\n"
            "**Example**: Swap 100 USDC for UNI\n"
            "```\n"
            "You pay:    100 USDC\n"
            "You receive: ~15.2 UNI  (estimated)\n"
            "```\n\n"
            "---\n\n"
            "## Step 4: Review Swap Details\n\n"
            "Before confirming, review:\n\n"
            "**Exchange Rate**:\n"
            "```\n"
            "1 USDC = 0.152 UNI\n"
            "1 UNI = 6.58 USDC\n"
            "```\n\n"
            "**Price Impact**: Should be < 1% for most trades\n"
            "- Green (< 1%): Good trade size\n"
            "- Yellow (1-3%): Acceptable but losing some value\n"
            "- Red (> 3%): Large slippage, consider splitting trade\n\n"
            "**Minimum Received**: Guaranteed minimum you'll get (accounting for slippage)\n"
            "```\n"
            "Minimum received: 15.05 UNI (0.5% slippage tolerance)\n"
            "```\n\n"
            "**Network Fee**: Ethereum gas cost\n"
            "```\n"
            "Network fee: ~$8.50 (varies with congestion)\n"
            "```\n\n"
            "**Click settings icon** (⚙️) to adjust:\n"
            "- **Slippage tolerance**: Default 0.5% (increase if transaction keeps failing)\n"
            "- **Transaction deadline**: Default 30 minutes\n\n"
            "---\n\n"
            "## Step 5: Approve Token (First Time Only)\n\n"
            "If swapping ERC-20 token (not ETH), you must approve Uniswap to spend your tokens.\n\n"
            "1. Click **Approve USDC** button\n"
            "2. MetaMask popup appears\n"
            "3. Review approval (default: unlimited)\n"
            "4. Click **Confirm** in MetaMask\n"
            "5. Wait for approval transaction (~30-60 seconds)\n\n"
            "**Note**: Approval costs gas (~$3-10) but only needed once per token\n\n"
            "**Approval amount options**:\n"
            "- **Unlimited**: Never approve again (convenient but slight security risk)\n"
            "- **Exact amount**: Approve only this swap (more secure but costs gas each time)\n\n"
            "---\n\n"
            "## Step 6: Execute Swap\n\n"
            "1. After approval (if needed), **Swap** button becomes active\n"
            "2. Click **Swap**\n"
            "3. Review final details in confirmation modal:\n"
            "   - Input amount\n"
            "   - Output amount (minimum)\n"
            "   - Price impact\n"
            "   - Fee\n"
            "4. Click **Confirm Swap**\n"
            "5. MetaMask popup appears with transaction details\n"
            "6. Review gas fee and click **Confirm**\n\n"
            "**Transaction submitted!**\n\n"
            "---\n\n"
            "## Step 7: Wait for Confirmation\n\n"
            "- Uniswap shows \"Transaction submitted\" with link to Etherscan\n"
            "- Click link to track transaction status\n"
            "- Wait for confirmation (15 seconds - 2 minutes typically)\n\n"
            "**Statuses**:\n"
            "- **Pending**: Transaction being processed by miners\n"
            "- **Success**: Swap completed! New tokens in your wallet\n"
            "- **Failed**: Transaction reverted (slippage too low, insufficient gas, etc.)\n\n"
            "---\n\n"
            "## Step 8: Verify Receipt\n\n"
            "After success:\n\n"
            "1. Open MetaMask\n"
            "2. Check that new tokens appear in your balance\n"
            "3. If token doesn't show, import it manually:\n"
            "   - MetaMask → **Import tokens**\n"
            "   - Paste token contract address (from Etherscan)\n\n"
            "---\n\n"
            "## Troubleshooting\n\n"
            "**\"Transaction failed\" / \"Price Impact Too High\"**\n\n"
            "**Cause**: Slippage tolerance too low or large trade for pool size\n\n"
            "**Fix**:\n"
            "- Increase slippage tolerance (⚙️ icon → 1% or 2%)\n"
            "- Split trade into smaller amounts\n"
            "- Wait for better liquidity\n\n"
            "**\"Insufficient liquidity\"**\n\n"
            "**Cause**: Not enough liquidity in pool for your trade size\n\n"
            "**Fix**:\n"
            "- Reduce trade amount\n"
            "- Try different DEX (SushiSwap, Curve)\n"
            "- Use DEX aggregator (1inch) to find best route\n\n"
            "**Gas fee too high?**\n\n"
            "**Fix**:\n"
            "- Wait for lower network congestion (check [Etherscan Gas Tracker](https://etherscan.io/gastracker))\n"
            "- Use Layer 2 (Uniswap on Arbitrum or Optimism for ~95% lower fees)\n"
            "- Weekends/late nights typically cheaper\n\n"
            "**Wrong token received**\n\n"
            "**Cause**: Selected wrong token (scam tokens with similar names)\n\n"
            "**Prevention**: Always verify token contract address before swapping\n\n"
            "---\n\n"
            "## Tips for Better Swaps\n\n"
            "**1. Check Price Impact**\n"
            "- Keep under 1% when possible\n"
            "- Split large trades to reduce slippage\n\n"
            "**2. Compare Prices**\n"
            "- Use [DEX aggregators](https://1inch.io) to find best rate\n"
            "- Compare Uniswap, SushiSwap, Curve\n\n"
            "**3. Time Your Trade**\n"
            "- Gas fees vary 5-10x depending on time of day\n"
            "- [Etherscan Gas Tracker](https://etherscan.io/gastracker) shows optimal times\n\n"
            "**4. Use Layer 2**\n"
            "- Uniswap available on Arbitrum, Optimism, Polygon\n"
            "- Same interface, 95% lower gas fees\n"
            "- Bridge assets first using [Uniswap Bridge](https://app.uniswap.org/bridge)\n\n"
            "---\n\n"
            "## Next Steps\n\n"
            "- **Provide liquidity**: Earn fees by becoming LP ([Uniswap Pool Guide](https://docs.uniswap.org))\n"
            "- **Try aggregators**: [1inch](https://1inch.io), [Matcha](https://matcha.xyz) for best prices\n"
            "- **Learn more**: [Uniswap University](https://uniswap.org/university)"
        ),
        sources=["Uniswap documentation", "DeFi user guides", "Web3 UX best practices"]
    ).with_inputs("goal"),
]